package com.steerinfo.dil.util;

import com.google.common.io.Files;
import com.steerinfo.dil.aspect.LogAspect;
import com.steerinfo.framework.exception.BaseException;
import com.steerinfo.framework.utils.io.FileUtils;
import com.steerinfo.framework.utils.misc.IdGenerator;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * @author lyg
 * @Description:
 * @CreateTime 2022/7/15 19:05
 * @Version:1.0
 */

    public class UploadUtils {
        public  static IdGenerator idGenerator = new IdGenerator(1,1);
        private static final Logger log = Logger.getLogger(UploadUtils.class);

        public UploadUtils() {
        }

        public static String uploadFile(MultipartFile file, String uploadPath, String imgPath) {
            String profilePhoto = null;
            if (file != null) {
                String fileId = idGenerator.getNextStr();
                String fileName = file.getOriginalFilename();
                String ext = Files.getFileExtension(fileName.toLowerCase());
                try {
                    String filePath = uploadPath + imgPath + fileId + "." + ext;
                    File newFile = new File(filePath);
                    FileUtils.makesureParentDirExists(newFile);
                    Files.write(file.getBytes(), newFile);
                } catch (IOException var10) {
                    throw new BaseException("上传文件为空:" + var10.getMessage());
                }

                profilePhoto = uploadPath + imgPath + fileId + "." + ext;
            }

            return profilePhoto;
        }

        public static byte[] imageToByte(String imgUrl) {
            if (StringUtils.isEmpty(imgUrl)) {
                return null;
            } else {
                File file = new File(imgUrl);
                byte[] data = null;
                if (file.exists()) {
                    String ext = Files.getFileExtension(imgUrl.toLowerCase());
                    ByteArrayOutputStream out = new ByteArrayOutputStream();

                    try {
                        BufferedImage bi = ImageIO.read(file);
                        ImageIO.write(bi, ext, out);
                        data = out.toByteArray();
                    } catch (FileNotFoundException var7) {
                        var7.printStackTrace();
                    } catch (IOException var8) {
                        var8.printStackTrace();
                    }
                }

                return data;
            }
        }
    }


